import asyncio
import datetime
import os
import uuid

from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render, redirect
from django.template import loader

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from approve.models import Approve, ApprFlow, ApprRank, ApprHistory
from approve.serializer import ApproveSerializer, ApproveFlowSerializer
from jiuyun.settings import BASE_DIR
from user.models import Inform, Staff
from utils.decorator_ import PermissionCheck
from utils.picture import save_image_async


class ApprView(APIView):
    @PermissionCheck('approve.view_approve')
    def get(self, request, format=None):
        # 查询参数： page 页号, size 每页显示的条目数量
        page = int(request.GET.get('page', '1'))
        size = int(request.GET.get('size', '20'))
        if request.user:
            staff_id = request.user.staff_id
            staff = Staff.objects.get(pk=staff_id)
            print(staff)
            if staff.role.role_id in ['4a1286cefec64c74a39b7fa18a0a6848', '4c2a53b3843e49ebadc4eb56b6f7e86b']:
                data = Approve.objects.all()
            else:
                data = Approve.objects.filter(staff_num=staff.num)
            paginator = Paginator(data, size)
            pager = paginator.page(page)
            # 模型实例化
            approve = ApproveSerializer(pager.object_list, many=True)
            return Response({
                'data': approve.data,
                'total': paginator.count,
                'page': pager.number,  # page当前页号
                'pageSize': size,
                'pages': paginator.num_pages  # 总页数
            })

    @PermissionCheck('approve.add_approve')
    def post(self, request, format=None):
        staff_id = request.user.staff_id
        appr_id = uuid.uuid4().hex
        start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        content = request.data.get('content')
        appr_kind = request.data.get('kind')
        approvers_list = request.data.get('approvers')
        if Approve.objects.all():
            ret = str(Approve.objects.count() + 1)
            anum = 'A' + ret.rjust(9, '0')
        else:
            anum = 'A' + '1'.rjust(9, '0')
        if Inform.objects.all():
            ret = str(Inform.objects.count() + 1)
            inum = 'I' + ret.rjust(9, '0')
        else:
            inum = 'I' + '1'.rjust(9, '0')
        if staff_id:
            Approve.objects.create(appr_id=appr_id, num=anum, staff_id=staff_id, start_time=start_time, status="待审批",
                                   content=content, appr_kind=appr_kind)
            for appr in range(len(approvers_list)):
                ApprRank.objects.create(rank_id=uuid.uuid4().hex,
                                        appr_id=appr_id,
                                        rank=appr + 1,
                                        staff_id=approvers_list[appr],
                                        status="待审批")
            ApprFlow.objects.create(flow_id=uuid.uuid4().hex,
                                    appr_id=appr_id,
                                    staff_id=approvers_list[0],
                                    status="待审批")
            Inform.objects.create(inform_id=uuid.uuid4().hex,
                                  num=inum,
                                  staff_name=Staff.objects.get(pk=approvers_list[0]).name,
                                  staff_num=Staff.objects.get(pk=approvers_list[0]).num,
                                  time=start_time,
                                  event=content,
                                  status='未读')
            return Response({'msg': '审批提交成功'}, status=status.HTTP_201_CREATED)
        return Response({'msg': '审批提交出错，请重试'})

    @PermissionCheck('approve.change_apprflow')
    def put(self, request, format=None):
        staff_id = request.user.staff_id
        appr_id = request.data.get('approve')
        idea = request.data.get('idea')
        content = request.data.get('content')
        ret = ApprFlow.objects.filter(Q(appr_id=appr_id) & Q(staff_id=staff_id))
        appr_flow = None
        if ret.exists():
            appr_flow = ret.first()
            appr_flow.idea = idea
            appr_flow.content = content
        if Inform.objects.all():
            num = str(Inform.objects.count() + 1)
            inum = 'I' + num.rjust(9, '0')
        else:
            inum = 'I' + '1'.rjust(9, '0')
        if idea == '同意':
            appr_flow.status = '通过'
            appr_flow.appr_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            rank = ApprRank.objects.filter(Q(appr_id=appr_id) & Q(staff=staff_id))
            appr_rank = None
            if rank.exists:
                appr_rank = rank.first()
                appr_rank.status = '通过'
                ApprHistory.objects.create(apprhis_id=uuid.uuid4().hex,
                                           num=Approve.objects.get(appr_id=appr_flow.appr_id).num,
                                           staff_id=Approve.objects.get(appr_id=appr_flow.appr_id).staff_id,
                                           start_time=appr_flow.appr_time,
                                           finish_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                           status='通过',
                                           appr_kind=Approve.objects.get(appr_id=appr_flow.appr_id).appr_kind,
                                           appr_name=Staff.objects.get(staff_id=appr_flow.staff_id).name,
                                           appr_idea=idea,
                                           appr_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                           start_cont=content,
                                           content=content)
            next_rank = ApprRank.objects.filter(Q(appr_id=appr_id) & Q(rank=appr_rank.rank + 1))
            # 创建下一位流程
            if next_rank.exists():
                ApprFlow.objects.create(flow_id=uuid.uuid4().hex,
                                        appr_id=next_rank.first().appr_id,
                                        staff_id=next_rank.first().staff_id,
                                        status="待审批")
                Inform.objects.create(inform_id=uuid.uuid4().hex,
                                      num='I' + str(Inform.objects.count() + 1).rjust(9, '0'),
                                      staff_name=Staff.objects.get(pk=next_rank.first().staff_id).name,
                                      staff_num=Staff.objects.get(pk=next_rank.first().staff_id).num,
                                      time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), event="未处理审批",status='未读')
            else:
                appr = Approve.objects.get(appr_id=appr_id)
                appr.status = '通过'
                appr.content = appr_flow.content
                appr.finish_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                appr.save()
                Inform.objects.create(inform_id=uuid.uuid4().hex, num=inum,
                                      staff_name=Staff.objects.get(pk=appr.staff_id).name,
                                      staff_num=Staff.objects.get(pk=appr.staff_id).num,
                                      time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), event='审批通过',status='未读')
            appr_rank.save()
        else:
            appr_flow.status = '未通过'
            appr = Approve.objects.get(appr_id=appr_id)
            appr.status = '未通过'
            appr.content = appr_flow.content
            appr.finish_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            appr.save()
            rank = ApprRank.objects.filter(Q(appr_id=appr_id) & Q(staff=staff_id))
            rank.first().status = appr_flow.status
            rank.first().save()
            ApprHistory.objects.create(apprhis_id=uuid.uuid4().hex,
                                       num=Approve.objects.get(appr_id=appr_flow.appr_id).num,
                                       staff_id=Approve.objects.get(appr_id=appr_flow.appr_id).staff_id,
                                       start_time=appr_flow.appr_time,
                                       finish_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                       status='未通过',
                                       appr_kind=Approve.objects.get(appr_id=appr_flow.appr_id).appr_kind,
                                       appr_name=staff_id,
                                       appr_idea=idea,
                                       appr_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                       start_cont=content,
                                       content=content)
        appr_flow.save()
        return Response({'msg': '修改成功'})

class ApprFlowView(APIView):
    # 查看审批流程
    @PermissionCheck('approve.view_apprflow')
    def get(self, request, apprid, format=None):
        approve = ApproveFlowSerializer(ApprFlow.objects.filter(appr__appr_id=apprid), many=True)
        return Response(approve.data)

class ApprUpdateView(APIView):
    def put(self, request, format=None):
        appr_id = request.data.get('approve_id')
        for i in ApprRank.objects.filter(appr_id=appr_id):
            if i.status == '同意':
                continue
            elif i.status == '不同意':
                ret = Approve.objects.get(appr_id=i.appr_id)
                ret.status = '未通过'
                flow = ApprFlow.objects.filter(appr_id=i.appr_id).last()
                ret.content = flow.content
                ret.save()
                data = ApproveSerializer(Approve.objects.get(appr_id=i.appr_id), many=False)
                return Response({'msg': '更新成功', 'data': data.data})
            elif i.status == '未审批':
                ApprFlow.objects.create(flow_id=uuid.uuid4().hex,
                                        appr_id=i.appr_id,
                                        staff=i.staff_id,
                                        appr_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                        status='未审批'
                                        )
                data = ApproveSerializer(Approve.objects.get(appr_id=i.appr_id), many=False)
                return Response({'msg': '更新成功', 'data': data.data})
        ret = Approve.objects.get(appr_id=appr_id)
        ret.status = '通过'
        ret.save()
        data = ApproveSerializer(Approve.objects.get(appr_id=appr_id), many=False)
        return Response({'msg': '更新成功', 'data': data.data})


class ApprimgView(APIView):
    def get(self,reqest,pk,format=None):
        appr = Approve.objects.get(pk=pk)
        user = Staff.objects.get(pk=appr.staff_id)
        apprflow = ApprFlow.objects.filter(appr_id=pk)
        appr1 = apprflow[0]
        appr2 = apprflow[1]

        dir_path = r'F:\python_code\djangoapps\jiuyun'
        img_path = r'%s\media\approve\%s.png' % (dir_path, appr.num)
        print('-->img_path', img_path)

        content = loader.render_to_string('approve.html', locals(), reqest)
        tmp_file_path = os.path.join(BASE_DIR, 'tmp.html')
        with open(tmp_file_path, 'w', encoding='utf-8') as f:
            f.write(content)

        from xmlrpc.client import ServerProxy
        sp = ServerProxy('http://localhost:9800')
        sp.save_image(tmp_file_path, img_path)

        return redirect(f'/media/approve/{appr.num}.png')

